package com.pureut.quality.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.quality.domain.*;
import com.pureut.quality.domain.dto.SampleInspectionDto;
import com.pureut.quality.domain.vo.*;
import com.pureut.quality.mapper.*;
import com.pureut.quality.service.*;
import com.pureut.system.api.FeignService;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.api.vo.SysAuditHistoryVo;
import com.pureut.system.api.vo.SysWorkbenchAuditAgentVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/***
 * 样品管理实现层
 * Author:C
 * Date:2023/02/07 10:29
 * @DESC
 */
@Service
public class QualitySampleInformationServiceImpl extends ServiceImpl<QualitySampleInformationMapper, QualitySampleInformation> implements QualitySampleInformationService {

    @Resource
    QualityInspectionDocumentService qualityInspectionDocumentService;

    @Resource
    QualityInspectionDocumentMapper qualityInspectionDocumentMapper;

    @Resource
    QualityBadSampleService qualityBadSampleService;

    @Resource
    QualityBadSampleMapper qualityBadSampleMapper;

    @Resource
    QualityCheckDocMapper qualityCheckDocMapper;

    @Resource
    QualitySampleInformationMapper qualitySampleInformationMapper;

    @Resource
    QualityTemporaryMapper qualityTemporaryMapper;

    @Resource
    QualityTemporaryService qualityTemporaryService;

    @Resource
    QualitySchemeConfigurationMapper qualitySchemeConfigurationMapper;

    @Resource
    QualitySchemeConfigurationDetailMapper qualitySchemeConfigurationDetailMapper;

    @Resource
    PublicProjectMapper publicProjectMapper;

    @Resource
    IQualityInspectionService qualityInspectionItemService;

    @Resource
    FeignService feignService;

    @Resource
    PublicProjectService publicProjectService;

    @Resource
    QualityInventoryRecheckMapper qualityInventoryRecheckMapper;

    @Resource
    QualityInventoryRecheckService qualityInventoryRecheckService;


    /**
     * 保存（样品信息）
     *
     * @param sampleAddVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(SampleAddVo sampleAddVo) {
        List<SampleInspectionVo> sampleInspectionList = sampleAddVo.getSampleInspectionList();
        //获取对应的检验单
        QualityInspectionDocument byId = qualityInspectionDocumentService.getById(sampleAddVo.getId());
        //判断检验进度是否已经达到要求
        //已经检验过的物料列表
        List<QualityTemporary> qualityTemporaryList = qualityTemporaryMapper.selectList(new QueryWrapper<QualityTemporary>().lambda().eq(QualityTemporary::getInspectionSheetNo, byId.getInspectionSheetNo()).eq(QualityTemporary::getInspectionMark, 1));
        QualitySchemeConfigurationVo qualitySchemeConfigurationVo = new QualitySchemeConfigurationVo();
        qualitySchemeConfigurationVo.setItemRank(byId.getItemRank());
        qualitySchemeConfigurationVo.setMaterialCode(byId.getMaterialCode());
        qualitySchemeConfigurationVo.setMaterialCategory(byId.getMaterialCategory());
        qualitySchemeConfigurationVo.setCategory(byId.getCategory());
        qualitySchemeConfigurationVo.setInspectionSheetNo(byId.getInspectionSheetNo());
        //应检数量
        int totalSize = qualityTemporaryService.getTotalSize(qualitySchemeConfigurationVo);
        if (totalSize == qualityTemporaryList.size()) {
            throw new GlobalException("应检物料已经达到要求");
        }

        List<QualitySampleInformation> qualitySampleInformationList = new ArrayList<>();

        for (SampleInspectionVo entity : sampleInspectionList) {
            QualitySampleInformation qualitySampleInformation = new QualitySampleInformation();
            qualitySampleInformation.setSampleNumber(sampleAddVo.getMaterialNumber())
                    .setItemId(entity.getId())
                    .setActualValue(entity.getActualValue())
                    .setAverageValue(String.valueOf(entity.getAverageValue()))
                    .setInspectionResults(entity.getInspectionResults())
                    .setBadId(entity.getBadId())
                    .setInspectionSheetNo(sampleAddVo.getInspectionSheetNo());
            qualitySampleInformationList.add(qualitySampleInformation);
        }
        saveBatch(qualitySampleInformationList);
        //保存样本检验结果
        QualityBadSample qualityBadSample = new QualityBadSample();
        qualityBadSample.setSampleNumber(sampleAddVo.getMaterialNumber())
                .setInspectionBy(SecurityUtils.getUsername())
                .setInspectionTime(new Date())
                .setCreateTime(new Date())
                .setDeptId(SecurityUtils.getDeptId())
                .setInspectionSheetNo(sampleAddVo.getInspectionSheetNo());
        //获取不良数量
        List<QualitySampleInformation> collect = qualitySampleInformationList.stream().filter(entity -> !(entity.getBadId() == null)).collect(Collectors.toList());
        qualityBadSample.setDefectiveQuantity(Long.parseLong(String.valueOf(collect.size())));

        //获取检验结果
        List<SampleInspectionVo> collect1 = sampleInspectionList.stream().filter(entity -> entity.getIsAverage() == 2).collect(Collectors.toList());
        if (collect1.size() > 0) {
            boolean isAll = true;
            for (SampleInspectionVo entity : collect1) {
                if (entity.getInspectionResults() == 2) {
                    isAll = false;
                    break;
                }
            }
            if (isAll) {
                qualityBadSample.setInspectionResults(1);
            } else {
                qualityBadSample.setInspectionResults(2);
            }
        } else {
            qualityBadSample.setInspectionResults(sampleInspectionList.get(0).getInspectionResults());
        }

        //查询是否已经保存过
        List<QualityBadSample> qualityBadSample1 = qualityBadSampleMapper.selectList(new QueryWrapper<QualityBadSample>().lambda().eq(QualityBadSample::getSampleNumber, sampleAddVo.getMaterialNumber()).eq(QualityBadSample::getInspectionSheetNo, byId.getInspectionSheetNo()));
        //如果是复检的单据
        if (qualityBadSample1.size() < 1) {
            qualityBadSampleService.save(qualityBadSample);
        } else {
            throw new GlobalException("该样品已经检验过");
        }
        //修改检验单据状态
        if (byId.getStatus() != 5) {
            byId.setStatus(2);
            qualityInspectionDocumentService.updateById(byId);
            //回传库存复检单据状态
            QualityInventoryRecheck qualityInventoryRecheck = qualityInventoryRecheckMapper.selectOne(new QueryWrapper<QualityInventoryRecheck>().lambda().eq(QualityInventoryRecheck::getReInspectionSheetNo, byId.getAssociatedNo()));
            if (qualityInventoryRecheck != null) {
                qualityInventoryRecheck.setStatus(byId.getStatus());
                qualityInventoryRecheckService.updateById(qualityInventoryRecheck);
            }
        } else {
            qualityInspectionDocumentService.updateById(byId);
        }

        //修改来料信息状态
        QualityTemporary qualityTemporary = qualityTemporaryMapper.selectOne(new QueryWrapper<QualityTemporary>().lambda().eq(QualityTemporary::getMaterialNumber, sampleAddVo.getMaterialNumber()).eq(QualityTemporary::getInspectionSheetNo, sampleAddVo.getInspectionSheetNo()));
        qualityTemporary.setInspectionMark(1);
        qualityTemporary.setInspectionBy(SecurityUtils.getUsername());
        qualityTemporary.setInspectionTime(new Date());
        qualityTemporary.setInspectionResults(qualityBadSample.getInspectionResults());

        return qualityTemporaryService.updateById(qualityTemporary);
    }


    /**
     * 保存（大）
     *
     * @param addDocumentVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addDocument(AddDocumentVo addDocumentVo) {

        //获取检验单据配置
        QualityCheckDoc qualityCheckDoc = qualityCheckDocMapper.selectOne(new QueryWrapper<QualityCheckDoc>().lambda().eq(QualityCheckDoc::getItemRank, addDocumentVo.getItemRank()).eq(QualityCheckDoc::getMaterialType, addDocumentVo.getCategory()));
        //获取检验单数据
        QualityInspectionDocument qualityInspectionDocument = qualityInspectionDocumentService.getById(addDocumentVo.getId());
        //未通过情况下进行大保存时修改审核历史数据
        if (qualityInspectionDocument.getStatus() == 5) {
            SysAuditHistoryVo sysAuditHistoryVo = new SysAuditHistoryVo();
            String perms = "quality:inspecmanage:testbill:batchAudit";
            String auditDoc = qualityInspectionDocument.getInspectionSheetNo();
            sysAuditHistoryVo.setAuditDoc(auditDoc);
            sysAuditHistoryVo.setPerms(perms);
            AjaxResult history = feignService.editHistory(sysAuditHistoryVo);
            String data = JSON.parseObject(JSON.toJSONString(history.get("msg")), String.class);
            qualityInspectionDocument.setStatus(3);
            qualityInspectionDocumentService.updateById(qualityInspectionDocument);
        }
        //获取该单据的检验项目
        List<SampleInspectionDto> sampleInspection = addDocumentVo.getSampleInspection();
        //获取检验样品结果数据
        List<QualityBadSample> qualityBadSamples = qualityBadSampleMapper.selectList(new QueryWrapper<QualityBadSample>().lambda().eq(QualityBadSample::getInspectionSheetNo, addDocumentVo.getInspectionSheetNo()));
        //获取样本结果数据
        List<SampleInspectionDto> list = getList(addDocumentVo.getInspectionSheetNo());
        //获取已经检验过的物料信息列表
        List<QualityTemporary> qualityTemporaryList = qualityTemporaryMapper.selectList(new QueryWrapper<QualityTemporary>().lambda().eq(QualityTemporary::getInspectionSheetNo, addDocumentVo.getInspectionSheetNo()).eq(QualityTemporary::getInspectionMark, 1));
        //如果应检数量和已经检验过的物料信息数相等
        QualitySchemeConfigurationVo qualitySchemeConfigurationVo = new QualitySchemeConfigurationVo();
        qualitySchemeConfigurationVo.setItemRank(qualityInspectionDocument.getItemRank());
        qualitySchemeConfigurationVo.setMaterialCode(qualityInspectionDocument.getMaterialCode());
        qualitySchemeConfigurationVo.setMaterialCategory(qualityInspectionDocument.getMaterialCategory());
        qualitySchemeConfigurationVo.setCategory(qualityInspectionDocument.getCategory());
        qualitySchemeConfigurationVo.setInspectionSheetNo(qualityInspectionDocument.getInspectionSheetNo());
        //应检数量
        int totalSize = qualityTemporaryService.getTotalSize(qualitySchemeConfigurationVo);

        if (totalSize != qualityTemporaryList.size()) {
            throw new GlobalException("样品没有检验完毕，不能进行此操作");
        }
        //判断单据中是否全为勾选平均值判定的
        boolean isAll = true;
        for (SampleInspectionDto entity : sampleInspection) {
            if (entity.getIsAverage() == 2) {
                isAll = false;
                break;
            }
        }
        //判断单据中是否全为未勾选平均值判定的
        boolean isNotAll = true;
        for (SampleInspectionDto entity : sampleInspection) {
            if (entity.getIsAverage() == 1) {
                isNotAll = false;
                break;
            }
        }
        //如果单据中项目全是未勾选平均值判定的，则直接用样品检验结果合格不合格的比率跟设定的百分比比较来判定
        if (isNotAll) {
            //获取百分比
            String checkDecisionBasis = qualityCheckDoc.getCheckDecisionBasis();

            //判断合格数量是否达到
            BigDecimal bigDecimal = new BigDecimal(checkDecisionBasis);
            BigDecimal multiply = bigDecimal.multiply(new BigDecimal(qualityBadSamples.size()));
            BigDecimal divide = multiply.divide(new BigDecimal(100), 0);
            //获取合格数量
            List<QualityBadSample> collect = qualityBadSamples.stream().filter(entity -> entity.getInspectionResults() == 1).collect(Collectors.toList());
            if (collect.size() >= Integer.parseInt(String.valueOf(divide))) {
                //合格
                //检验结果
                qualityInspectionDocument.setInspectionResults(1);
                //判定等级
                qualityInspectionDocument.setJudgmentGrade(1);
                //单据状态
                qualityInspectionDocument.setStatus(3);
                //设置应检数量
                List<QualityTemporary> qualityTemporaryList1 = qualityTemporaryMapper.selectList(new QueryWrapper<QualityTemporary>().lambda().eq(QualityTemporary::getInspectionSheetNo, addDocumentVo.getInspectionSheetNo()));
                qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityTemporaryList1.size())));
                //实际检验数量
                qualityInspectionDocument.setActualInspectionQuantity(Long.parseLong(String.valueOf(qualityBadSamples.size())));
                //不良数量
                BigDecimal bigDecimal1 = new BigDecimal(0);
                for (QualityBadSample entity : qualityBadSamples) {
                    bigDecimal1 = bigDecimal1.add(new BigDecimal(entity.getDefectiveQuantity()));
                }
                qualityInspectionDocument.setBadSampleNum(Long.parseLong(String.valueOf(bigDecimal1)));
            } else {
                //检验结果
                qualityInspectionDocument.setInspectionResults(2);
                //判定等级
//                qualityInspectionDocument.setJudgmentGrade(3);
                //单据状态
                qualityInspectionDocument.setStatus(3);
                //设置应检数量
                List<QualityTemporary> qualityTemporaryList1 = qualityTemporaryMapper.selectList(new QueryWrapper<QualityTemporary>().lambda().eq(QualityTemporary::getInspectionSheetNo, addDocumentVo.getInspectionSheetNo()));
                qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityTemporaryList1.size())));
                //实际检验数量
                qualityInspectionDocument.setActualInspectionQuantity(Long.parseLong(String.valueOf(qualityBadSamples.size())));
                //不良数量
                BigDecimal bigDecimal1 = new BigDecimal(0);
                for (QualityBadSample entity : qualityBadSamples) {
                    bigDecimal1 = bigDecimal1.add(new BigDecimal(entity.getDefectiveQuantity()));
                }
                qualityInspectionDocument.setBadSampleNum(Long.parseLong(String.valueOf(bigDecimal1)));
            }
            //回传库存复检单据状态
            QualityInventoryRecheck qualityInventoryRecheck = qualityInventoryRecheckMapper.selectOne(new QueryWrapper<QualityInventoryRecheck>().lambda().eq(QualityInventoryRecheck::getReInspectionSheetNo, qualityInspectionDocument.getAssociatedNo()));
            if (qualityInventoryRecheck != null) {
                qualityInventoryRecheck.setStatus(qualityInspectionDocument.getStatus());
                qualityInventoryRecheckService.updateById(qualityInventoryRecheck);
            }

            //修改审核代办状态为已处理
            feignService.updateStatus(3, qualityInspectionDocument.getInspectionSheetNo(), "检验单据");//

            //新增审核代办
            SysWorkbenchAuditAgentVo sysWorkbenchAuditAgentVo = new SysWorkbenchAuditAgentVo();

            sysWorkbenchAuditAgentVo.setDocConfig("quality:inspecmanage:testbill:batchAudit");
            sysWorkbenchAuditAgentVo.setReceiptName("检验单据");
            sysWorkbenchAuditAgentVo.setReceiptNumber(qualityInspectionDocument.getInspectionSheetNo());//
            sysWorkbenchAuditAgentVo.setStatus(1);//待审核
            sysWorkbenchAuditAgentVo.setReceiptContent("有单据待审核,请及时审核");

            feignService.insertAuditAgent(sysWorkbenchAuditAgentVo);

            return qualityInspectionDocumentService.updateById(qualityInspectionDocument);
        }


        //如果全为勾选了平均值,则需要计算单据中所有项目的每组平均值，一个平均值不在范围里面，单据（3号）就不合格
        if (isAll) {
            //根据项目id进行分组
            Map<Long, List<SampleInspectionDto>> collect = list.stream().collect(Collectors.groupingBy(SampleInspectionDto::getItemId));
            boolean isSuccess = true;
            for (Map.Entry<Long, List<SampleInspectionDto>> entity : collect.entrySet()) {
                List<SampleInspectionDto> value = entity.getValue();
                BigDecimal bigDecimal = new BigDecimal(0);

                //获取该组的平均值
                for (SampleInspectionDto sample : value) {
                    //将同组的平均值相加除以该组的数量
                    bigDecimal = bigDecimal.add(new BigDecimal(String.valueOf(sample.getAverageValue())));
                }
                BigDecimal divide = bigDecimal.divide(new BigDecimal(value.size()), 0);


                for (SampleInspectionDto sample : value) {
                    //判断divide是否在上下限范围之内
                    //判断divide是否在上下限范围之内
                    double k1 = divide.doubleValue();
                    double k2;
                    double k3;
                    if ("--".equals(sample.getItemLowerLimit())) {
                        k2 = 0;
                    } else {
                        k2 = Double.parseDouble(sample.getItemLowerLimit());
                    }

                    if ("--".equals(sample.getItemUpperLimit())) {
                        k3 = 0;
                    } else {
                        k3 = Double.parseDouble(sample.getItemUpperLimit());
                    }

                    if (k1 == 0) {
                        isSuccess = false;
                        break;
                    }

                    if (k1 < k2 || k1 > k3) {
                        isSuccess = false;
                        break;
                    }
                }

            }
            //如果不在范围之内，就是不合格，反之就是合格
            if (isSuccess) {
                //合格的情况
                //检验结果
                qualityInspectionDocument.setInspectionResults(1);
                //判定等级
                qualityInspectionDocument.setJudgmentGrade(1);
                //单据状态
                qualityInspectionDocument.setStatus(3);
                //设置应检数量
                List<QualityTemporary> qualityTemporaryList1 = qualityTemporaryMapper.selectList(new QueryWrapper<QualityTemporary>().lambda().eq(QualityTemporary::getInspectionSheetNo, addDocumentVo.getInspectionSheetNo()));
                qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityTemporaryList1.size())));
                //实际检验数量
                qualityInspectionDocument.setActualInspectionQuantity(Long.parseLong(String.valueOf(qualityBadSamples.size())));
                //不良数量
                BigDecimal bigDecimal1 = new BigDecimal(0);
                for (QualityBadSample entity : qualityBadSamples) {
                    bigDecimal1 = bigDecimal1.add(new BigDecimal(entity.getDefectiveQuantity()));
                }
                qualityInspectionDocument.setBadSampleNum(Long.parseLong(String.valueOf(bigDecimal1)));
            } else {
                //检验结果
                qualityInspectionDocument.setInspectionResults(2);
                //判定等级
//                qualityInspectionDocument.setJudgmentGrade(3);
                //单据状态
                qualityInspectionDocument.setStatus(3);
                //设置应检数量
                List<QualityTemporary> qualityTemporaryList1 = qualityTemporaryMapper.selectList(new QueryWrapper<QualityTemporary>().lambda().eq(QualityTemporary::getInspectionSheetNo, addDocumentVo.getInspectionSheetNo()));
                qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityTemporaryList1.size())));
                //实际检验数量
                qualityInspectionDocument.setActualInspectionQuantity(Long.parseLong(String.valueOf(qualityBadSamples.size())));
                //不良数量
                BigDecimal bigDecimal1 = new BigDecimal(0);
                for (QualityBadSample entity : qualityBadSamples) {
                    bigDecimal1 = bigDecimal1.add(new BigDecimal(entity.getDefectiveQuantity()));
                }
                qualityInspectionDocument.setBadSampleNum(Long.parseLong(String.valueOf(bigDecimal1)));
            }
            //回传库存复检单据状态
            QualityInventoryRecheck qualityInventoryRecheck = qualityInventoryRecheckMapper.selectOne(new QueryWrapper<QualityInventoryRecheck>().lambda().eq(QualityInventoryRecheck::getReInspectionSheetNo, qualityInspectionDocument.getAssociatedNo()));
            if (qualityInventoryRecheck != null) {
                qualityInventoryRecheck.setStatus(qualityInspectionDocument.getStatus());
                qualityInventoryRecheckService.updateById(qualityInventoryRecheck);
            }

            //修改审核代办状态为已处理
            feignService.updateStatus(3, qualityInspectionDocument.getInspectionSheetNo(), "检验单据");//

            //新增审核代办
            SysWorkbenchAuditAgentVo sysWorkbenchAuditAgentVo = new SysWorkbenchAuditAgentVo();

            sysWorkbenchAuditAgentVo.setDocConfig("quality:inspecmanage:testbill:batchAudit");
            sysWorkbenchAuditAgentVo.setReceiptName("检验单据");
            sysWorkbenchAuditAgentVo.setReceiptNumber(qualityInspectionDocument.getInspectionSheetNo());//
            sysWorkbenchAuditAgentVo.setStatus(1);//待审核
            sysWorkbenchAuditAgentVo.setReceiptContent("有单据待审核,请及时审核");

            feignService.insertAuditAgent(sysWorkbenchAuditAgentVo);


            return qualityInspectionDocumentService.updateById(qualityInspectionDocument);
        } else {
            //都存在的情况
            //根据项目id进行分组
            Map<Long, List<SampleInspectionDto>> collect = list.stream().collect(Collectors.groupingBy(SampleInspectionDto::getItemId));
            boolean isSuccess = true;
            for (Map.Entry<Long, List<SampleInspectionDto>> entity : collect.entrySet()) {
                List<SampleInspectionDto> value = entity.getValue();
                BigDecimal bigDecimal = new BigDecimal(0);
                //判断该检验项目是否勾选了平均值
                PublicProject publicProject = publicProjectService.getById(entity.getKey());
                if (publicProject.getIsAverage() == 1) {
                    for (SampleInspectionDto sample : value) {
                        //将同组的平均值相加除以该组的数量
                        bigDecimal = bigDecimal.add(new BigDecimal(String.valueOf(sample.getAverageValue())));
                    }
                    BigDecimal divide = bigDecimal.divide(new BigDecimal(value.size()), 0);
                    //判断divide是否在上下限范围之内
                    double k1 = divide.doubleValue();
                    double k2;
                    double k3;
                    if ("--".equals(publicProject.getItemLowerLimit())) {
                        k2 = 0;
                    } else {
                        k2 = Double.parseDouble(publicProject.getItemLowerLimit());
                    }

                    if ("--".equals(publicProject.getItemUpperLimit())) {
                        k3 = 0;
                    } else {
                        k3 = Double.parseDouble(publicProject.getItemUpperLimit());
                    }

                    if (k1 == 0) {
                        isSuccess = false;
                        break;
                    }

                    if (k1 < k2 || k1 > k3) {
                        isSuccess = false;
                        break;
                    }
                }
            }
            //如果都存在，就进行下一步校验，如果有一个不存在就为不合格
            if (isSuccess) {
                //获取百分比
                String checkDecisionBasis = qualityCheckDoc.getCheckDecisionBasis();

                //判断合格数量是否达到
                BigDecimal bigDecimal = new BigDecimal(checkDecisionBasis);
                BigDecimal multiply = bigDecimal.multiply(new BigDecimal(qualityBadSamples.size()));
                BigDecimal divide = multiply.divide(new BigDecimal(100), 0);
                //获取合格数量
                List<QualityBadSample> qualifiedCollect = qualityBadSamples.stream().filter(entity -> entity.getInspectionResults() == 1).collect(Collectors.toList());
                if (qualifiedCollect.size() >= Integer.parseInt(String.valueOf(divide))) {
                    //合格
                    //检验结果
                    qualityInspectionDocument.setInspectionResults(1);
                    //判定等级
                    qualityInspectionDocument.setJudgmentGrade(1);
                    //单据状态
                    qualityInspectionDocument.setStatus(3);
                    //设置应检数量
                    List<QualityTemporary> qualityTemporaryList1 = qualityTemporaryMapper.selectList(new QueryWrapper<QualityTemporary>().lambda().eq(QualityTemporary::getInspectionSheetNo, addDocumentVo.getInspectionSheetNo()));
                    qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityTemporaryList1.size())));
                    //实际检验数量
                    qualityInspectionDocument.setActualInspectionQuantity(Long.parseLong(String.valueOf(qualityBadSamples.size())));
                    //不良数量
                    BigDecimal bigDecimal1 = new BigDecimal(0);
                    for (QualityBadSample entity : qualityBadSamples) {
                        bigDecimal1 = bigDecimal1.add(new BigDecimal(entity.getDefectiveQuantity()));
                    }
                    qualityInspectionDocument.setBadSampleNum(Long.parseLong(String.valueOf(bigDecimal1)));
                } else {
                    //检验结果
                    qualityInspectionDocument.setInspectionResults(2);
                    //判定等级
//                    qualityInspectionDocument.setJudgmentGrade(3);
                    //单据状态
                    qualityInspectionDocument.setStatus(3);
                    //设置应检数量
                    List<QualityTemporary> qualityTemporaryList1 = qualityTemporaryMapper.selectList(new QueryWrapper<QualityTemporary>().lambda().eq(QualityTemporary::getInspectionSheetNo, addDocumentVo.getInspectionSheetNo()));
                    qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityTemporaryList1.size())));
                    //实际检验数量
                    qualityInspectionDocument.setActualInspectionQuantity(Long.parseLong(String.valueOf(qualityBadSamples.size())));
                    //不良数量
                    BigDecimal bigDecimal1 = new BigDecimal(0);
                    for (QualityBadSample entity : qualityBadSamples) {
                        bigDecimal1 = bigDecimal1.add(new BigDecimal(entity.getDefectiveQuantity()));
                    }
                    qualityInspectionDocument.setBadSampleNum(Long.parseLong(String.valueOf(bigDecimal1)));
                }
                //回传库存复检单据状态
                QualityInventoryRecheck qualityInventoryRecheck = qualityInventoryRecheckMapper.selectOne(new QueryWrapper<QualityInventoryRecheck>().lambda().eq(QualityInventoryRecheck::getReInspectionSheetNo, qualityInspectionDocument.getAssociatedNo()));
                if (qualityInventoryRecheck != null) {
                    qualityInventoryRecheck.setStatus(qualityInspectionDocument.getStatus());
                    qualityInventoryRecheckService.updateById(qualityInventoryRecheck);
                }
                //修改审核代办状态为已处理
                feignService.updateStatus(3, qualityInspectionDocument.getInspectionSheetNo(), "检验单据");//

                //新增审核代办
                SysWorkbenchAuditAgentVo sysWorkbenchAuditAgentVo = new SysWorkbenchAuditAgentVo();

                sysWorkbenchAuditAgentVo.setDocConfig("quality:inspecmanage:testbill:batchAudit");
                sysWorkbenchAuditAgentVo.setReceiptName("检验单据");
                sysWorkbenchAuditAgentVo.setReceiptNumber(qualityInspectionDocument.getInspectionSheetNo());//
                sysWorkbenchAuditAgentVo.setStatus(1);//待审核
                sysWorkbenchAuditAgentVo.setReceiptContent("有单据待审核,请及时审核");

                feignService.insertAuditAgent(sysWorkbenchAuditAgentVo);

                return qualityInspectionDocumentService.updateById(qualityInspectionDocument);

            } else {
                //检验结果
                qualityInspectionDocument.setInspectionResults(2);
                //判定等级
//                qualityInspectionDocument.setJudgmentGrade(3);
                //单据状态
                qualityInspectionDocument.setStatus(3);
                //设置应检数量
                List<QualityTemporary> qualityTemporaryList1 = qualityTemporaryMapper.selectList(new QueryWrapper<QualityTemporary>().lambda().eq(QualityTemporary::getInspectionSheetNo, addDocumentVo.getInspectionSheetNo()));
                qualityInspectionDocument.setQuantityInspected(Long.parseLong(String.valueOf(qualityTemporaryList1.size())));
                //实际检验数量
                qualityInspectionDocument.setActualInspectionQuantity(Long.parseLong(String.valueOf(qualityBadSamples.size())));
                //不良数量
                BigDecimal bigDecimal1 = new BigDecimal(0);
                for (QualityBadSample entity : qualityBadSamples) {
                    bigDecimal1 = bigDecimal1.add(new BigDecimal(entity.getDefectiveQuantity()));
                }
                qualityInspectionDocument.setBadSampleNum(Long.parseLong(String.valueOf(bigDecimal1)));
            }
            //回传库存复检单据状态
            QualityInventoryRecheck qualityInventoryRecheck = qualityInventoryRecheckMapper.selectOne(new QueryWrapper<QualityInventoryRecheck>().lambda().eq(QualityInventoryRecheck::getReInspectionSheetNo, qualityInspectionDocument.getAssociatedNo()));
            if (qualityInventoryRecheck != null) {
                qualityInventoryRecheck.setStatus(qualityInspectionDocument.getStatus());
                qualityInventoryRecheckService.updateById(qualityInventoryRecheck);
            }

            //修改审核代办状态为已处理
            feignService.updateStatus(3, qualityInspectionDocument.getInspectionSheetNo(), "检验单据");//

            //新增审核代办
            SysWorkbenchAuditAgentVo sysWorkbenchAuditAgentVo = new SysWorkbenchAuditAgentVo();

            sysWorkbenchAuditAgentVo.setDocConfig("quality:inspecmanage:testbill:batchAudit");
            sysWorkbenchAuditAgentVo.setReceiptName("检验单据");
            sysWorkbenchAuditAgentVo.setReceiptNumber(qualityInspectionDocument.getInspectionSheetNo());//
            sysWorkbenchAuditAgentVo.setStatus(1);//待审核
            sysWorkbenchAuditAgentVo.setReceiptContent("有单据待审核,请及时审核");

            feignService.insertAuditAgent(sysWorkbenchAuditAgentVo);

            return qualityInspectionDocumentService.updateById(qualityInspectionDocument);
        }
    }


    /**
     * 样品列表
     *
     * @param inspectionSheetNo
     * @return
     */
    @Override
    public List<SampleInspectionDto> getList(String inspectionSheetNo) {
        QualityInspectionDocument qualityInspectionDocument = qualityInspectionDocumentMapper.selectOne(new QueryWrapper<QualityInspectionDocument>().lambda().eq(QualityInspectionDocument::getInspectionSheetNo, inspectionSheetNo));

        //管控方式
        List<SysDictData> controlModeArray = DictUtils.getDictCache("quality_item_control_mode");
        Map<String, String> controlModeMap = controlModeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //检验结果
        List<SysDictData> resultsArray = DictUtils.getDictCache("quality_inspection_results");
        Map<String, String> resultsMap = resultsArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //不良等级
        List<SysDictData> badLevelArray = DictUtils.getDictCache("quality_bad_level");
        Map<String, String> badLevelMap = badLevelArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

//        List<QualitySchemeConfigurationDetail> details = null;
//        QualitySchemeConfigurationVo qualitySchemeConfigurationVo = new QualitySchemeConfigurationVo();
//        qualitySchemeConfigurationVo.setCategory(qualityInspectionDocument.getCategory());
//        qualitySchemeConfigurationVo.setItemRank(qualityInspectionDocument.getItemRank());
//        qualitySchemeConfigurationVo.setMaterialCode(qualityInspectionDocument.getMaterialCode());
//        qualitySchemeConfigurationVo.setMaterialCategory(qualityInspectionDocument.getMaterialCategory());
        //根据阶别、类别、方案类型、物料编码查询检验项目
//        Long byCodeIds = qualitySchemeConfigurationMapper.getConfigurationListByCode(qualitySchemeConfigurationVo);
//        if (byCodeIds != null) {
//            //获取该id下的明细
//            details = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().in(QualitySchemeConfigurationDetail::getSchemeId, byCodeIds));
//        } else {
//            //根据阶别、类别、方案类型、物料类别查询检验项目
//            Long byCategoryIds = qualitySchemeConfigurationMapper.getConfigurationListByCategory(qualitySchemeConfigurationVo);
//            if (byCategoryIds != null) {
//                //获取该id下的明细
//                details = qualitySchemeConfigurationDetailMapper.selectList(new QueryWrapper<QualitySchemeConfigurationDetail>().lambda().in(QualitySchemeConfigurationDetail::getSchemeId, byCategoryIds));
//            }
//        }
        List<PublicProject> publicProjectList = publicProjectMapper.selectList(new QueryWrapper<PublicProject>().lambda().eq(PublicProject::getInspectionSheetNo, qualityInspectionDocument.getInspectionSheetNo()));
        if (publicProjectList.size() < 1) {
            throw new GlobalException("未找到配置的项目");
        }
        List<SampleInspectionDto> informationList = qualitySampleInformationMapper.getInformationList(inspectionSheetNo);

        for (SampleInspectionDto entity : informationList) {
//            List<ActualValueVo> actualValueList = entity.getActualValueList();
            List<ActualValueVo> objects = new ArrayList<>();

            List<String> averageValues = Arrays.asList(entity.getActualValue().split(","));
            for (String averageValue : averageValues) {
                ActualValueVo actualValueVo = new ActualValueVo();
                actualValueVo.setActualValue(averageValue);
                objects.add(actualValueVo);
            }
            for (PublicProject detail : publicProjectList) {
                if (entity.getItemId().equals(detail.getItemId())) {
                    entity.setItemLowerLimit(detail.getItemLowerLimit());
                    entity.setItemUpperLimit(detail.getItemUpperLimit());
                    entity.setItemName(detail.getItemName());
                    //管控方式
                    entity.setItemControlModeDict(controlModeMap.get(String.valueOf(detail.getItemControlMode())));
                    entity.setItemCheckContent(detail.getItemCheckContent());
                }
            }
            entity.setActualValueList(objects);

            //检验结果
            entity.setInspectionResultsDict(resultsMap.get(entity.getInspectionResults()));
            //不良等级
            entity.setBadGradeDict(badLevelMap.get(entity.getBadGrade()));
        }
        return informationList;
    }
}
